package com.mid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lxk on 2020/1/18.
 */
public class Solution12 {

    public static final Map<String, String> cur2Romain = new HashMap<>();

    static {
        //key中前一位表示数字中哪一位，后一位表示该数字中该位的数值
        cur2Romain.put("0-", "I");
        cur2Romain.put("04", "IV");     //4
        cur2Romain.put("0+", "V");
        cur2Romain.put("09", "IX");     //9
        cur2Romain.put("1-", "X");
        cur2Romain.put("14", "XL");     //40
        cur2Romain.put("1+", "L");
        cur2Romain.put("19", "XC");     //90
        cur2Romain.put("2-", "C");
        cur2Romain.put("24", "CD");     //400
        cur2Romain.put("2+", "D");
        cur2Romain.put("29", "CM");     //900
        cur2Romain.put("3-", "M");

    }

    public String intToRoman(int num) {
        if (num > 3999 || num < 1) {
            return null;
        }
        List<String> romainNums = new ArrayList<>();
        int level = 0;
        while (num != 0) {
            int curNum = num % 10;
            num = num / 10;
            String curStr = null;
            if (curNum == 4) {
                curStr = cur2Romain.get(level + "" + curNum);
            } else if (curNum == 9) {
                curStr = cur2Romain.get(level + "" + curNum);
            } else {
                if (curNum < 5) {
                    //小于5时，直接多个基数1连接
                    StringBuffer tempCurNum = new StringBuffer();
                    for (int i = 0; i < curNum; i++) {
                        tempCurNum.append(cur2Romain.get(level + "-"));
                    }
                    curStr = tempCurNum.toString();
                } else if (curNum >= 5) {
                    //大于等于5，需要一个基数5，然后基数1连接
                    StringBuffer tempCurNum = new StringBuffer();
                    tempCurNum.append(cur2Romain.get(level + "+"));
                    int remainNum = curNum - 5;
                    for (int i = 0; i < remainNum; i++) {
                        tempCurNum.append(cur2Romain.get(level + "-"));
                    }
                    curStr = tempCurNum.toString();
                }
            }
            romainNums.add(curStr);
            level++;
        }
        StringBuffer res = new StringBuffer();
        for (int i = romainNums.size() - 1; i >= 0; i--) {
            res.append(romainNums.get(i));
        }
        return res.toString();
    }

}
